#coding:utf-8

import time
import subprocess,os
   
COUNT_TOTAL = 10  #总共ping的次数
COUNT = 1      #单次ping的次数
COUNT_FILE = 1 #ping多少次写一次文件
TIMEOUT = 10000 #超时时间设置，单位毫秒


fileName = time.strftime("%Y%m%d%H",time.localtime()) #文件名以时间明名
WriterFile = "/sdcard/sl4a/log/ping_result_"+fileName+".txt"
LogFile = "/sdcard/sl4a/log/"+fileName+".log"

def Makepath(Path):       
    '''建立目录'''
    if not os.path.exists(Path):   #路径是否存在，不存在就新建
        os.makedirs(Path)    
    else:
        print "Path exists:" + Path
        
def writeFile(fileName,strList):
    f = open(fileName,"a+")
    if type(strList) == type([]):
        for str in strList:
            f.write(str)
    elif type(strList) == type(""):
        f.write(strList)
    f.close()

def ping(count,byteSizes,Seq):
    cmd = 'su -c "ping -c '+str(count)+' -s '+str(byteSizes)+' 58.251.149.108"'  #执行的ping命令
    filesLog = open(LogFile,"a+")  #创建filesLog文件对象，写入ping超时，错误记录信息

    result_list = []

    #p=subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True) #调用系统的管道执行命令
    #list = p.stdout.readlines()   #将执行后的结果存入list列表中
    p = os.popen(cmd)   
    list = p.readlines() #将执行后的结果存入list列表中
    p.close()

    readFlag = False
    readTag = 0
    for i in range(len(list)):
        #if list[i].find("packets received,") != -1:
        if list[i].find("received,") != -1:
            readFlag = True
            readTag = i
    if readFlag == True:   #判断结果信息中是否存在最终的统计信息
        start = list[readTag].find("transmitted,")
        #end = list[readTag].find("packets received")
        end = list[readTag].find("received")
        receivedCount = int(list[readTag][start+12:end].replace(" ",""))  #统计收到的包数
        for info in list:    
            if info.find("bytes from") != -1:
                start = info.find("time=")
                end = info.find("ms")
                times = int(float(info[start+5:end].replace(" ","")))  #计算该ping的延时时间
                result_list.append(str(Seq)+","+str(byteSizes)+","+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())+ ","+str(times)+",0\n")
                if len(result_list) == COUNT_FILE:
                    writeFile(WriterFile,result_list)
                    result_list = []
        if receivedCount != count: 
            nLoss = count - receivedCount
            filesLog.write(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())+"\n") 
            for msg in list: #将有超时记录的信息的ping记录写入log文件
                filesLog.write(msg)
            for i in range(nLoss):  #将丢失包的记录写文件
                result_list.append(str(Seq)+","+str(byteSizes)+","+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())+",,1\n")
                if len(result_list) == COUNT_FILE:
                    writeFile(WriterFile,result_list)
                    result_list = []
    else: #将无统计信息的错误ping信息记录到log中
        for msg in list:
            filesLog.write(msg)
    filesLog.close()

if __name__ == "__main__":
    print "start ping ..."
    Makepath("/sdcard/sl4a/log/")
    ByteSizes = [1792,1536,1280,1024,768,512,256,128,96,64,32]
    number = 0
    c = 0
    while (COUNT_TOTAL/COUNT)>number:
        number += 1
        for size in ByteSizes:
            c += 1
            ping(COUNT,size,c)
    print "end ping ..."
